package juc.cas;

public class TestCompareAndSwap {
    public static void main(String[] args) {
         CompareAndSwap cas = new CompareAndSwap();

        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                int expectedValue = cas.get();
                boolean b = cas.compareAndSet(expectedValue, (int) (Math.random() * 101));
                System.out.println(b);

            }).start();
        }
    }
}

class CompareAndSwap {
    private int value;

    /**
     * 获取内存值
     *
     * @return
     */
    public synchronized int get() {
        return value;
    }

    /**
     * 比较并交换
     *
     * @param expected
     * @param newValue
     * @return
     */
    public synchronized int compareAndSwap(int expected, int newValue) {
        int oldValue = value;
        if (expected == oldValue) {
            this.value = newValue;
        }
        return oldValue;
    }

    /**
     * 比较并设置值
     *
     * @param expected
     * @param newValue
     * @return
     */
    public synchronized boolean compareAndSet(int expected, int newValue) {
        return expected == compareAndSwap(expected, newValue);
    }
}
